import React from 'react';
import { red } from '@ant-design/colors';
import { CloseCircleOutlined, FrownOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Button, Result, Typography } from 'antd';

const { Paragraph } = Typography;

export class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    // 更新 state 使下一次渲染能够显示降级后的 UI
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    this.setState({
      error: error,
      errorInfo: errorInfo,
    });
    // 同样可以将错误日志上报给服务器
    setTimeout(() => {
      if (this.state.hasError) throw (error, errorInfo);
    });
  }

  componentDidMount() {
    this.prevPath = window.location.pathname;
  }

  componentDidUpdate() {
    if (window.location.pathname !== this.prevPath) {
      this.setState({ error: null, errorInfo: null, hasError: false });
    }
    this.prevPath = window.location.pathname;
  }

  renderError() {
    if (this.state.errorInfo) {
      return (
        <ProCard
          ghost
          style={{
            marginTop: '16px',
            backgroundColor: '#f5f5f5',
            textAlign: 'left',
            fontSize: '8px',
          }}
        >
          {this.state.error.stack
            .split('\n')
            .splice(0, 3)
            .map((e, i) => (
              <Paragraph key={i} style={{ color: '#8c8c8c' }}>
                <CloseCircleOutlined
                  style={{
                    color: red[5],
                    paddingRight: '8px',
                    fontSize: '12px',
                  }}
                />
                {JSON.stringify(e)}
              </Paragraph>
            ))}
        </ProCard>
      );
    }
  }

  render() {
    if (this.state.hasError) {
      return (
        <Result
          style={{ marginTop: '10vh' }}
          title="系统出了 Bug，请找工程师帮忙解决，或者点右下角反馈"
          subTitle={this.renderError()}
          icon={<FrownOutlined />}
          extra={[
            <Button
              type="primary"
              key="toHome"
              onClick={() => window.location.replace('/')}
            >
              回到首页
            </Button>,
            <Button key="reload" onClick={() => window.location.reload()}>
              刷新页面
            </Button>,
          ]}
        />
      );
    }
    return this.props.children;
  }
}
